//获取应用实例
const app = getApp();
const util = require('../../utils/util.js');
const {
  $Toast
} = require('../../dist/base/index');
var pageNo = 1;
Page({
  data: {
    current: -1, //当前所在滑块的 index
    scrollLeft: 0, //滚动条的位置,一个选项卡宽度是90（自定义来自css），按比例90*n设置位置
    navlist: ["全部", "NodeJS", "Nginx", "前端", "数据库"],
    content: [],
    tip: "",
    loading: false,
    userInfo: {},
    user_comment: '',
    isShow: true,
    show: false,
    buttons: [{
        type: 'error',
        className: 'screenDialog',
        text: '编辑草稿',
        value: 0
      },
      {
        type: 'primary',
        className: 'screenDialog',
        text: '修改文章',
        value: 1
      }
    ]
  },

  buttontap(e) {
		var that = this;
    this.setData({
      show: false
    });
    if (e.detail.index == 0) {
			wx.setStorage({
				key: 'isEdit',
				data: true,
			})
			wx.navigateTo({
				url: '/pages/writearticle/writearticle',
			});
    } else {
			wx.request({
				url: util.basePath + '/article/v1/articleDetail/' + that.data.article_uid,
				method: "post",
				data: {
       
				},
				header: {
					'content-type': 'application/json'
				},
				success(res) {
					if (res.data.status == 200) {
						that.alterArticle(res.data.payload);
					} else {
						$Toast({
							content: res.data.err,
							type: 'error'
						});
					}
				}
			});
    }
  },

  //tab切换
  tab: function(event) {
    var cateUrl = this.data.navlist[event.target.dataset.current].labels;
    var that = this;
    pageNo = 1;
    this.setData({
      current: event.target.dataset.current,
      content: []
    });

    wx.request({
      url: util.basePath + '/article/v1/getLabelsArticle',
      method: "post",
      data: {
        cateUrl: cateUrl,
        openid: that.data.userInfo.openid,
        app_sid: that.data.userInfo.app_sid,
        page: pageNo
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.data.status == 200) {
          that.setData({
            content: that.data.content.concat(res.data.payload)
          });
        } else {
          $Toast({
            content: res.data.err,
            type: 'error'
          });
          that.setData({
            content: [],
            isShow: false
          });
        }
      }
    });
  },

  onLoad: function(options) {
    var that = this;

    var userInfo = wx.getStorageSync("loginInfo");
    if (!userInfo) {
      wx.reLaunch({
        url: '/pages/userinfo/userinfo',
      });
    }
    that.setData({
      userInfo: userInfo
    });

    that.getUserDesignArticle();
  },

  onPullDownRefresh: function() {
    wx.showNavigationBarLoading();
    this.data.content = [];
    pageNo = 1;
    this.getUserDesignArticle();

    setTimeout(function() {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh()
    }, 1000);
  },

  onReachBottom: function() {
    var that = this;
    ++pageNo;
    this.getUserDesignArticle();

  },

  modifyArticle: function(e) {
    var index = e.currentTarget.dataset.index;
    var that = this;
		that.setData({article_uid: index});

    wx.showActionSheet({
      itemList: ['修改', '删除'],
      success: function(res) {
        //修改文章
        if (res.tapIndex == 0) {
          //判断草稿箱是否有文章
          wx.request({
            url: util.basePath + '/article/v1/checkDraftContent',
            method: "post",
            data: {
              openid: wx.getStorageSync("loginInfo").openid,
              app_sid: wx.getStorageSync("loginInfo").app_sid
            },
            header: {
              'content-type': 'application/json'
            },
            success(res) {
              if (res.data.status == 200) {
                if (res.data.payload.count == 1) {
                  that.setData({
                    show: true,
                    article_title: res.data.payload.title
                  })
                } else {
                  wx.request({
                    url: util.basePath + '/article/v1/articleDetail/' + index,
                    method: "post",
                    data: {

                    },
                    header: {
                      'content-type': 'application/json'
                    },
                    success(res) {
                      if (res.data.status == 200) {
                        that.alterArticle(res.data.payload);
                      } else {
                        $Toast({
                          content: res.data.err,
                          type: 'error'
                        });
                      }
                    }
                  });
                }
              } else {
                $Toast({
                  content: res.data.err,
                  type: 'error'
                });
              }
            }
          });
        } else {
          //弹出对话框
          wx.showModal({
            title: '警告',
            content: '确定删除文章?',
            success: function(res) {
              if (res.confirm) {
                wx.request({
                  url: util.basePath + '/article/v1/deleteArticle/' + index,
                  method: "post",
                  data: {

                  },
                  header: {
                    'content-type': 'application/json'
                  },
                  success(res) {
                    if (res.data.status == 200) {
                      $Toast({
                        content: '删除文章成功!',
                        type: 'warn'
                      });

                      that.getUserDesignArticle();
                    } else {
                      $Toast({
                        content: res.data.err,
                        type: 'error'
                      });
                    }
                  }
                });
              }
            }
          });
        }
      }
    });
  },

  alterArticle: function(article) {
    if (!article.article_content || !article.article_img) {
      $Toast({
        content: '无权限操作',
        type: 'error'
      });
    } else {
      article.article_content = article.article_content.split('===');
      article.article_img = article.article_img.split('===');
			if (article.file_type) {
				article.file_type = article.file_type.split('===');
			}
			
			this.delDraftContent();
			this.changeContentStatus(article);

      wx.setStorage({
        key: 'alterArticle',
        data: {
          id: article.id,
          title: article.title,
          author: article.author,
          labels: article.labels,
          article_img: article.article_img,
          article_content: article.article_content,
					file_type: article.file_type
        }
      });

      wx.navigateTo({
        url: '/pages/writearticle/writearticle',
      });
    }
  },

	changeContentStatus: function (article) {
		var that = this;

		wx.request({
			url: util.basePath + '/article/v1/changeContentStatus',
			method: "post",
			data: {
				id: article.id
			},
			header: {
				'content-type': 'application/json'
			},
			success(res) {
				if (res.data.status != 200) {
					$Toast({
						content: res.data.err,
						type: 'error'
					});
				}
			}
		});
	},

	delDraftContent: function () {
		var that = this;

		wx.request({
			url: util.basePath + '/article/v1/delDraftContent',
			method: "post",
			data: {
				openid: wx.getStorageSync("loginInfo").openid,
				app_sid: wx.getStorageSync("loginInfo").app_sid
			},
			header: {
				'content-type': 'application/json'
			},
			success(res) {
				if (res.data.status != 200) {
					$Toast({
						content: res.data.err,
						type: 'error'
					});
				}
			}
		});
	},

  onShareAppMessage: function(res) {
    return {
      title: '个人主页',
      path: '/pages/logs/logs'
    }
  },
  details(e) {
    //详情页跳转
    wx.navigateTo({
      url: '../details/details?id=' + e.currentTarget.id
    })
  },
  getUserDesignArticle: function() {
    var that = this;
    that.setData({
      loading: true,
      tip: "正在加载"
    });

    wx.request({
      url: util.basePath + '/article/v1/getUserArticleAndCategories',
      method: "post",
      data: {
        app_sid: that.data.userInfo.app_sid,
        openid: that.data.userInfo.openid,
        page: pageNo
      },
      dataType: 'json',
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.data.status == 200) {
          that.setData({
            loading: false,
            tip: "没有数据了",
            content: that.data.content.concat(res.data.payload.data),
            navlist: res.data.payload.labels
          });
        } else {
          that.setData({
            loading: false,
            tip: "没有数据了"
          });
        }
      }
    });
  }
});